//
//  KKXuanShangDetailVC.m
//  DoMi
//
//  Created by 康凯 on 2016/12/6.
//  Copyright © 2016年 kk. All rights reserved.
//

#import "KKXuanShangDetailVC.h"
#import "KKPublishXuanShangVC.h"
#import "KKJoinXuanShangVC.h"
#import "KKXuanShangDetailCell.h"
#import "KKComHttp.h"
#import "KKQuestionDetailM.h"
#import "KKQuestionDetailListM.h"
#import "KKXuanShangInfoVC.h"
#import "KKShareDialog.h"
#import "KKXuanShangRuleView.h"
#import "KKMyHttp.h"

@interface KKXuanShangDetailVC ()<UITableViewDelegate,UITableViewDataSource>{
    int countTime;
}

@property (weak, nonatomic) IBOutlet UIImageView *avatar;
@property (weak, nonatomic) IBOutlet UILabel *nickname;
@property (weak, nonatomic) IBOutlet UILabel *job;
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UILabel *title1;
@property (weak, nonatomic) IBOutlet UILabel *content;
@property (weak, nonatomic) IBOutlet UILabel *time;
@property (weak, nonatomic) IBOutlet UILabel *answerCount;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *money;
@property (weak, nonatomic) IBOutlet UILabel *countDownTime;

@property (strong, nonatomic)KKQuestionDetailM *questionInfo;
@property (strong, nonatomic)NSArray *questionDatas;
@property (strong, nonatomic)NSTimer *timer;
@property (weak, nonatomic) IBOutlet UIView *xuanShangInfoView;
@property (weak, nonatomic) KKXuanShangRuleView *rule;
@property (weak, nonatomic) IBOutlet UIView *xuanShangView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *xuanShangViewHeight;
@property (weak, nonatomic) IBOutlet UIButton *xuanShangRule;

@end

@implementation KKXuanShangDetailVC

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.rule dismiss];
    [self.timer invalidate];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getQuestionDetail)];
    [self.tableView.mj_header beginRefreshing];
}
-(void)dealloc{
    [self.timer invalidate];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //右侧分享
    UIButton *rightBtn = [[UIButton alloc ]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [rightBtn setImage:[UIImage imageNamed:@"sharebgblack"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.title=@"悬赏详情";
    //tableview
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.rowHeight=80;
    [self.tableView registerNib:[UINib nibWithNibName:@"KKXuanShangDetailCell" bundle:nil] forCellReuseIdentifier:@"KKXuanShangDetailCell"];
    //悬赏详情
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushXSDetail)];
    [self.xuanShangInfoView addGestureRecognizer:tap];
}

-(void)scheduleTime{
    self.timer=[NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        if(countTime>0){
            self.countDownTime.text=[NSString stringWithFormat:@"距悬赏结束还有%@",[KKAppUtils timeformatFromSeconds:countTime]];
            countTime--;
        }
        else{
            [self.timer invalidate];
            self.countDownTime.text=[NSString stringWithFormat:@"悬赏已经结束"];
        }
        
    }];
}
-(void)initData{
    [self.avatar sd_setImageWithURL:[NSURL URLWithString:self.questionInfo.avatar] placeholderImage:[UIImage imageNamed:@"default_avater"]];
    if([KKAppUtils isEmptyString:self.questionInfo.nickname]){
        self.nickname.text=@"匿名";
    }else{
        self.nickname.text=self.questionInfo.nickname;
    }
    self.job.text=self.questionInfo.job;
    self.label.text=self.questionInfo.label;
    self.title1.text=self.questionInfo.title;
    self.content.text=self.questionInfo.questiondesc;
    self.answerCount.text=[NSString stringWithFormat:@"回答(%@)",self.questionInfo.answercoun];
    
    if([self.questionInfo.money isEqualToString:@"0.00"]){
        self.xuanShangRule.hidden=YES;
        self.xuanShangViewHeight.constant=0;
        self.xuanShangView.hidden=YES;
        self.time.text=@"";
    }else{
        self.xuanShangViewHeight.constant=50;
        self.xuanShangView.hidden=NO;
        //0未开始 1已开始 2 已结束
        if(self.questionInfo.status==0){
            self.countDownTime.text=@"悬赏尚未开始";
        }else if(self.questionInfo.status==1){
            NSString *time=[KKAppUtils timeformatFromSeconds:[self.questionInfo.lefttime intValue]];
            self.countDownTime.text=[NSString stringWithFormat:@"距离结束还有%@",time];
            countTime=[self.questionInfo.lefttime intValue];
            [self scheduleTime];
        }else{
            self.countDownTime.text=@"悬赏已经结束";
        }
        self.money.text=[NSString stringWithFormat:@"%.1f元",[self.questionInfo.money floatValue]];
    }
    self.time.text=self.questionInfo.systime;
}

#pragma mark tableview代理
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    KKXuanShangDetailCell *detail=(KKXuanShangDetailCell *)cell;
    if(indexPath.row<5){
        detail.rankImg.hidden=NO;
        [detail.rankImg setImage:[UIImage imageNamed:[NSString stringWithFormat:@"rank%ld",indexPath.row+1]]];
    }else{
        detail.rankImg.hidden=YES;
    }
    [detail initData:self.questionDatas[indexPath.row]];
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.questionDatas.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView dequeueReusableCellWithIdentifier:@"KKXuanShangDetailCell"];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    KKQuestionDetailListM *detail= self.questionDatas[indexPath.row];
    KKXuanShangInfoVC *info=[[KKXuanShangInfoVC alloc] init];
    info.questionId=self.questionId;
    info.answerId=detail.respondid;
    info.answerCon=detail.respondcontent;
    info.answerLikeCount=detail.likecoun;
    info.publishId=detail.uid;
    info.xuanShangMoney=self.questionInfo.money;
    info.questionUid=self.questionInfo.uid;
    info.navTitle=@"回答详情";
    info.answerInfo=detail;
    [self.navigationController pushViewController:info animated:YES];
}
#pragma mark 按钮--活动规则
- (IBAction)ruleClick:(id)sender {
    KKXuanShangRuleView *rule=[[[NSBundle mainBundle] loadNibNamed:@"KKXuanShangRuleView" owner:self options:nil] lastObject];
    self.rule=rule;
    [rule show];
}
#pragma mark 按钮--参加悬赏
- (IBAction)joinClick:(id)sender {
    [KKMyHttp userCheck:^(id data) {
        if([UID isEqualToString:self.questionInfo.uid]){
            [self toast:@"不能回答自己发布的"];
            return;
        }
        if(![self.questionInfo.money isEqualToString:@"0.00"]){
            if(self.questionInfo.status==2){
                [KKAppUtils toast:@"悬赏已经结束"];
                return;
            }
        }
        [self getQuestionCheck];
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark 按钮--发布悬赏
- (IBAction)publishClick:(id)sender {
    KKPublishXuanShangVC *publish=[[KKPublishXuanShangVC alloc] init];
    publish.publishSuccessBlock=^(){
        [self.tableView.mj_header beginRefreshing];
    };
    [self.navigationController pushViewController:publish animated:YES];
}
#pragma mark 按钮--悬赏详情
-(void)pushXSDetail{
    KKXuanShangInfoVC *info=[[KKXuanShangInfoVC alloc] init];
    info.questionId=self.questionId;
    info.xuanShangMoney=self.questionInfo.money;
    info.publishId=self.questionInfo.uid;
    info.navTitle=@"悬赏详情";
    [self.navigationController pushViewController:info animated:YES];
}
#pragma mark 按钮--分享
-(void)share{
    KKShareDialog *share=[[[NSBundle mainBundle] loadNibNamed:@"KKShareDialog" owner:self options:nil] lastObject];
    share.shareCallbackBlock=^(int flag){
        if(flag==0){
            [KKAppUtils toast:@"分享失败"];
        }else{
            
        }
    };
    [share show];
}

#pragma mark 接口--获取悬赏详情
-(void)getQuestionDetail{
    [KKComHttp getQuestionDetail:self.questionId success:^(id data) {
        if(self.timer.isValid){
            [self.timer invalidate];
        }
        self.questionInfo=data;
        self.questionDatas=self.questionInfo.list;
        [self.tableView reloadData];
        [self initData];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
    }];
}
#pragma mark 接口--悬赏权限检测
-(void)getQuestionCheck{
    [KKComHttp questionCheck:self.questionId success:^(id data) {
        KKJoinXuanShangVC *join=[[KKJoinXuanShangVC alloc] init];
        join.joinXSBlock=^(){
            if(self.timer.isValid){
                [self.timer invalidate];
            }
            //        [self getQuestionDetail];
        };
        join.questionId=self.questionId;
        join.xuanShangMoney=self.xuanShangMoney;
        [self.navigationController pushViewController:join animated:YES];
    } failure:^(NSError *error) {
        
    }];
}
@end
